<?php

namespace app\admin\controller;

use app\common\controller\Backend;


/**
 * WorkerMan 开发助手
 *
 * @icon fa fa-circle-o
 */
class Fastworker extends Backend
{

    protected $noNeedRight = ['*'];
    protected $isWin;
    protected $allowFields = [
        'server' => ['host','port','name','count','protocol','daemon'],
        'gateway'  => [],
        'timer' => ['execution','interval','daemon','single']
    ];

    protected $deployFields = [
        'register' => ['rhost','rport'],
        'business' => ['bname','bcount','event'],
        'gateway' => ['host','port','protocol','name','count','lanip','gport','pil','pnrl','daemon','initiative']
    ];


    public function _initialize()
    {
        parent::_initialize();
        $this->isWin = ('\\' === DIRECTORY_SEPARATOR);
    }


    public function index()
    {
        $this->view->assign("actionList", self::getActionList());
        $this->view->assign("protocolList", self::getProtocolList());
        return $this->view->fetch();
    }

    private function getProtocolList(){
        return ['websocket'=>'websocket','http'=>'http','text'=>'text','tcp'=>'tcp', 'udp'=>'udp', 'unix'=>'unix'];
    }

    private function getActionList(){
        $actionList = ['start'=>'启动', 'stop'=>'停止', 'reload'=>'重载', 'restart'=>'重启', 'status'=>'查看运行情况', 'connections'=>'查看TCP连接'];
        if ($this->isWin ) {
            $actionList = ['start'=>'启动'];
        }
        return $actionList;
    }


    /**
     * 生成命令行
     */
    public function command()
    {
        $commandType = $this->request->post("commandtype");
        $params = $this->request->post();
        if('start' !== $params['action']){
            $this->success("", null, ['command' => 'php think fastworker:'.$commandType.' '.$params['action']]);
        }

        if(!isset($this->allowFields[$commandType])){
            $this->error('Error Params');
        }

        if($this->isWin){
            $command = $this->commandParseWin($params,$commandType);
        }else{
            $command = $this->commandParse($params,$commandType);
        }

        $this->success("", null, ['command' => $command]);
    }

    private function commandParse($params,$commandType){
        if(isset($params['deploy']) && is_array($params['deploy'])){
            foreach ($params['deploy'] as $v){
                $this->allowFields['gateway'] = array_merge($this->allowFields['gateway'],$this->deployFields[$v]);
            }
            $argv[] = '--deploy '.implode(' --deploy ',$params['deploy']);
        }

        if(isset($params['action'])){
            $argv[] = $params['action'];
        }
        // 设置服务类其他参数不生效
        if('server' === $commandType && isset($params['class']) && is_array($params['class'])){
            $argv[] = '--class '.implode(' --class ',$params['class']);
        }else{
            $allowFields = array_filter(array_intersect_key($params, array_flip($this->allowFields[$commandType])));

            foreach ($allowFields as $key => $param) {
                $argv[] =  "--{$key} " . trim($param);
            }

        }
        return 'php think fastworker:'.$commandType.' '. implode(' ', $argv);
    }

    private function commandParseWin($params,$commandType){
        if('gateway' === $commandType){
            $commandArr = [];
            if(isset($params['deploy']) && is_array($params['deploy'])){
                foreach ($params['deploy'] as $v){
                    $allowFields = array_filter(array_intersect_key($params, array_flip($this->deployFields[$v])));
                    $command = 'start  php think fastworker:gateway --deploy '.$v;
                    foreach ($allowFields as $key => $param) {
                        $command .=  " --{$key} " . trim($param);
                    }
                    $commandArr[] = $command;
                }
            }else{
                foreach ($this->deployFields as $key => $v){
                    $command = 'start  php think fastworker:gateway --deploy '.$key;
                    $commandArr[] = $command;
                }
            }
            return implode('  &  ',$commandArr);
        }

        $argv = [];

        if(isset($params['action'])){
            $argv[] = $params['action'];
        }
        // 设置服务类其他参数不生效
        if('server' === $commandType && isset($params['class']) && is_array($params['class'])){
            if(count($params['class']) > 1){
                $this->error('windows下仅可设置一个服务类');
            }
            $argv[] = '--class '.implode(' --class ',$params['class']);
        }else{
            $allowFields = array_filter(array_intersect_key($params, array_flip($this->allowFields[$commandType])));

            foreach ($allowFields as $key => $param) {
                $argv[] =  "--{$key} " . trim($param);
            }
        }

        return 'php think fastworker:'.$commandType.' '. implode(' ', $argv);

    }

}
